using System.Linq;
using System.Windows;
using System.Windows.Controls;
using MinoChat.ViewModels.Pages;

namespace MinoChat.Views.Pages;

public partial class SettingsPage : UserControl
{
    private readonly SettingsPageViewModel _viewModel;
    private bool _isUpdatingPassword = false;
    private bool _isUpdatingTheme = false;

    public SettingsPage(SettingsPageViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;
        _viewModel = viewModel;

        // 监听 ViewModel 的属性变化，同步到 PasswordBox
        _viewModel.PropertyChanged += (s, e) =>
        {
            if (e.PropertyName == nameof(SettingsPageViewModel.CurrentProviderApiKey) && !_isUpdatingPassword)
            {
                _isUpdatingPassword = true;
                ApiKeyPasswordBox.Password = _viewModel.CurrentProviderApiKey;
                _isUpdatingPassword = false;
            }

            // 监听主题变化，同步到RadioButton
            if (e.PropertyName == nameof(SettingsPageViewModel.SelectedTheme) && !_isUpdatingTheme)
            {
                UpdateThemeSelection(_viewModel.SelectedTheme);
            }
        };

        // 设置初始值
        ApiKeyPasswordBox.Password = _viewModel.CurrentProviderApiKey;

        // 页面加载完成后设置主题选中状态
        Loaded += (s, e) => UpdateThemeSelection(_viewModel.SelectedTheme);
    }

    /// <summary>
    /// PasswordBox 密码变化事件处理
    /// </summary>
    private void ApiKeyPasswordBox_PasswordChanged(object sender, System.Windows.RoutedEventArgs e)
    {
        if (!_isUpdatingPassword && sender is PasswordBox passwordBox)
        {
            _isUpdatingPassword = true;
            _viewModel.CurrentProviderApiKey = passwordBox.Password;
            _isUpdatingPassword = false;
        }
    }

    /// <summary>
    /// 主题RadioButton选中事件处理
    /// </summary>
    private void ThemeRadioButton_Checked(object sender, RoutedEventArgs e)
    {
        if (_isUpdatingTheme || sender is not RadioButton radioButton)
            return;

        _isUpdatingTheme = true;
        var theme = radioButton.Tag?.ToString();
        if (!string.IsNullOrEmpty(theme))
        {
            _viewModel.SelectedTheme = theme;
        }
        _isUpdatingTheme = false;
    }

    /// <summary>
    /// 根据主题名称更新RadioButton选中状态
    /// </summary>
    private void UpdateThemeSelection(string theme)
    {
        _isUpdatingTheme = true;

        foreach (var child in ThemeButtonGroup.Children.OfType<RadioButton>())
        {
            child.IsChecked = child.Tag?.ToString() == theme;
        }

        _isUpdatingTheme = false;
    }
}